# -*- coding: utf-8 -*-
"""
Web framework/Tornado Locale/test02.py
"""
import os
import tornado.locale
import tornado.web
import asyncio


class IndexHandler(tornado.web.RequestHandler):
    def prepare(self):
        p_lang = self.get_argument("lang", default=None)
        locales = tornado.locale.get_supported_locales()
        if p_lang in locales:
            tornado.locale.set_default_locale(p_lang)
            self.locale = tornado.locale.get(p_lang)
        else:
            self.write("Language scripting is not supported, en_US is used by default.")

    def get(self):
        _ = self.locale.translate
        r_message = _(u"lang")
        self.finish(r_message)


async def main():
    locale_path = os.getcwd() + "/mo"
    tornado.locale.load_gettext_translations(directory=locale_path, domain="lang")
    app = tornado.web.Application([
        (r"/", IndexHandler)
    ])
    app.listen(8888)
    await asyncio.Event().wait()


if __name__ == '__main__':
    asyncio.run(main())

# > curl http://127.0.0.1:8888/?lang=zh_CN
# > HTTP Response: 欢迎访问当前api.
